package com.foin.city.presenter.impl;

import android.os.AsyncTask;

import com.foin.city.CityActivity;
import com.foin.city.bean.City;
import com.foin.city.bean.CityData;
import com.foin.city.presenter.ICityPresenter;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CityPresenterImpl implements ICityPresenter {

    private CityActivity mView;

    public CityPresenterImpl(CityActivity view) {
        mView = view;
    }

    /**
     * 查询全国城市列表
     */
    @Override
    public void selectCity() {
        new CityReaderAsyncTask().execute();
    }

    /**
     * 异步查询全国城市列表
     */
    private class CityReaderAsyncTask extends AsyncTask<Object, Void, List<City>> {

        @Override
        protected List<City> doInBackground(Object... objects) {
            InputStream in = null;
            List<City> cityList = new ArrayList<>();
            try {
                in = mView.getResources().getAssets().open("city.json");
                // 获取文件的字节数
                int length = in.available();
                // 创建byte数组
                byte[] buffer = new byte[length];
                // 将文件中的数据读到byte数组中
                in.read(buffer);
                String result = new String(buffer, "UTF-8");
                Gson gson = new Gson();
                CityData data = gson.fromJson(result, CityData.class);
                for (int i = 0; i < data.getCity().size(); i++) {
                    for (int i1 = 0; i1 < data.getCity().get(i).getList().size(); i1++) {
                        City city = new City();
                        city.setLetter(data.getCity().get(i).getInitial());
                        city.setName(data.getCity().get(i).getList().get(i1).getName());
                        cityList.add(city);
                    }
                }
            } catch (Exception e) {

            } finally {
                try {
                    in.close();
                } catch (IOException e) {

                }
            }
            return cityList;
        }

        @Override
        protected void onPostExecute(List<City> cityList) {
            super.onPostExecute(cityList);
            mView.onGetCitySuccess(cityList);
        }
    }
}
